import config from '@/config/config.js';
import { getToken } from '@/utils/auth';
import tool from '@/utils/common.js';
let timeout = 10000
const baseUrl = config.baseUrl
const upload = config => {
	const isToken = (config.headers || {}).isToken === false
	config.header = config.header || {};
	config.header['Content-Type'] = 'application/x-www-form-urlencoded';
	if(getToken() && isToken) {config.header['Authorization'] = uni.getStorageSync('token_type')+' ' + uni.getStorageSync('token')};
	// if(getToken() && isToken) {config.header['Authorization'] = 'Bearer ' + uni.getStorageSync('token')};
	if (config.params) {
		let url = config.url + '?' + tool.tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			timeout: config.timeout || timeout,
			url: baseUrl + config.url,
			filePath: config.filePath,
			name: config.name || 'file',
			header: config.header,
			formData: config.formData,
			success: (response) => {
				let result = JSON.parse(response.data)
				const code = result.code || 200
				if (code === 200) {
					resolve(result)
				} else if (code == 401) {
					tool.toastTip(result.msg||'无效的会话，或者会话已过期，请重新登录。','none',1000);
					setTimeout(()=>{uni.navigateTo({url:'/pages/login/login'})},1000)
					break;
				} else if (code === 500) {
					tool.toastTip(result.msg||'系统内部发生错误，请稍后重试！','none',1000);
				} else if (code !== 200) {
					tool.toastTip(result.msg||'系统繁忙，请稍后重试！','none',1000);
				}
				resolve(response.data)
			},
			fail: (error) => {
				let {msg} = error
				if (msg === 'Network Error') {
					msg = '后端接口连接异常'
				} else if (msg.includes('timeout')) {
					msg = '系统接口请求超时'
				} else if (msg.includes('Request failed with status code')) {
					msg = '系统接口' + msg.substr(msg.length - 3) + '异常'
				}
				reject(error)
			}
		})
	})
}
export default upload
